<template>
  <el-container class="list">
    <el-aside width="150px">
      <avue-tree :permission="categoryPermission" :option="categoryOption" :data="typeList"
                 @node-click="nodeClick"
                 @save="handleAddCategory"
                 @update="handleUpdateCategory"
                 @del="handleDelCategory"
                 class="custom-tree">
        <span class="el-tree-node__label" slot-scope="{node,data}" >
          <span> {{ node.label }}</span>
        </span>
      </avue-tree>
    </el-aside>
    <div class="list">
      <el-header class="content__header" v-if="hasAddPermission" >
        <p class="avue-tip-title" >选择下面的方式进行创建</p>
        <div class="content__box content__nav" >
          <div class="content__add"
               @click="handleAdd" >
            <img src="`${$router.options.base}img/new-project.png`"
                 height="40px"
                 alt="">
            <p>新建大屏</p>
          </div>
          <div class="content__page">
            <el-pagination v-if="page.total>0"
                           layout="total, sizes, prev, pager, next, jumper"
                           background
                           size="mini"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :page-size="page.size"
                           :current-page="page.page"
                           :total="page.total">
            </el-pagination>
          </div>
        </div>
      </el-header>
      <el-container>
      <el-main class="content">
        <div class="content__box">
          <div class="content__item"
               v-for="(item,index) in visualList"
               :key="index"
               @mouseover="item._menu=true"
               @mouseout="item._menu=false">
            <div class="content__info">
              <img v-if="item.backgroundUrl"
                   :src="item.backgroundUrl"
                   alt="" />
              <div class="content__menu"
                   v-show="item._menu">
                <div class="content__btn"
                     @click="handleViews(item)">
                  预览<i class="el-icon-view"></i>
                </div>
                <div class="content__btn"
                     @click="handleEdit(item)" v-if="hasEditPermission">
                  开发<i class="el-icon-setting"></i>
                </div>
                <div class="content__btn"
                     @click="handleExport(item)">
                  导出
                </div>
              </div>
            </div>
            <div class="content__main">
              <span class="content__name">{{item.title}}</span>
              <div class="content__menulist">
                <div class="content__view">
                  <el-tooltip content="删除" v-if="hasDelPermission">
                    <i class="el-icon-delete"
                       @click="handleDel(item,index)"></i>
                  </el-tooltip>
                  <el-tooltip content="编辑" v-if="hasEditPermission">
                    <i class="el-icon-edit"
                       @click="handleUpdate(item,index)"></i>
                  </el-tooltip>
                  <el-tooltip content="复制">
                    <i class="el-icon-copy-document"
                       @click="handleCopy(item,index)"></i>
                  </el-tooltip>
                </div>
                <span class="content__status"
                      :class="{'content__status--active':item.status}">
                  {{item.status?'已发布':'未发布'}}
                </span>
              </div>

            </div>
          </div>
        </div>
      </el-main>
      </el-container>
    </div>
    <el-dialog title="编辑大屏"
               width="50%"
               :close-on-click-modal="false"
               :visible.sync="box">
      <avue-form :option="option"
                 v-model="form"
                 @submit="handleSave"></avue-form>
    </el-dialog>

    <el-dialog title="复制大屏"
               width="50%"
               :close-on-click-modal="false"
               :visible.sync="copy">
      <avue-form :option="copyOption"
                 v-model="copyForm"
                 @submit="confirmCopy"></avue-form>
    </el-dialog>

  </el-container>
</template>
<script>
import {copyObj, delObj, getCategory, getList, getObj, updateObj} from '@/api/visual';
import {viewHtml} from '@/utils/html'
import {mapGetters} from "vuex";
import {addObj,getList as getCategoryList,updateObj as updateCategory,delObj as delCategory} from "@/api/category";
import {deepClone} from "@/echart/util";
import {share2User, userSharedList} from "@/api/share";
import {groupBy, uuid} from "@/utils/utils";
import {addProject, deleteProject, updateProject} from "@/api/project";

export default {
  props:{
    project:{
      type: Object,
      default: {}
    },
    projectId:{
      type: String,
      default: null
    }
  },
  data () {
    return {
      typeList: [],
      categoryLoading: false,
      categoryFilterText: '',
      box: false,
      copy: false,
      categoryOption:{
        filterText:"分类名称",
        align: 'center',
        headerAlign: 'center',
        addBtn: false,
        formOption:{
          labelWidth:180,
          column: [
            {
              label: '模块名',
              prop: 'categoryKey',
              rules: [{
                required: true,
                message: "请输入模块名",
                trigger: "blur"
              }]
            },
            {
              label: '模块值',
              prop: 'categoryValue',
              placeholder: '自动生成，无需输入',
              disabled: true
            }
          ]
        },
        props:{
          labelText: '类目',
          label:'categoryKey',
          value:'categoryValue',
          children: 'children'
        }
      },
      option: {
        submitText: '修改大屏',
        column: [{
          label: '分组',
          prop: 'category',
          span: 24,
          labelWidth: 100,
          type: 'select',
          dicUrl: this.$website.url + '/category/list',
          props: {
            label: 'categoryKey',
            value: 'categoryValue',
          },
          rules: [{
            required: true,
            message: "请选择分组",
            trigger: "blur"
          }]
        }, {
          label: '大屏名称',
          span: 24,
          labelWidth: 100,
          prop: 'title',
          rules: [{
            required: true,
            message: "请输入大屏名称",
            trigger: "blur"
          }]
        }, {
          label: '密码',
          span: 24,
          type: 'password',
          labelWidth: 100,
          prop: 'password',
        }, {
          label: '发布状态',
          prop: 'status',
          span: 24,
          labelWidth: 100,
          type: 'select',
          dicData: [{
            label: '未发布',
            value: 0
          }, {
            label: '已发布',
            value: 1
          }]
        }]
      },
      copyOption: {
        submitText: '确认复制',
        column: [{
          label: '复制到',
          prop: 'copyTo',
          type: 'select',
          dicData: [
            {label: "个人空间",value: 0},
            {label: "本项目空间",value: 1},
          ],
          props: {
            label: 'label',
            value: 'value',
          },
          change:({value,column})=>{
            if(value ===1){
              this.copyOption.column[1].dicUrl=this.$website.url+`category/list?projectId=`+this.projectId
            }else {
              this.copyOption.column[1].dicUrl=this.$website.url+`category/list`
            }
          },
          cascaderItem:['category'],
          rules: [{
            required: true,
            message: "请选择复制到的空间",
            trigger: "blur"
          }]
        },{
          label: '分组',
          prop: 'category',
          span: 24,
          labelWidth: 100,
          type: 'select',
          cascaderIndex:0,
          dicUrl: this.$website.url+`category/list`,
          props: {
            label: 'categoryKey',
            value: 'categoryValue',
          },
          rules: [{
            required: true,
            message: "请选择分组",
            trigger: "blur"
          }]
        }, {
          label: '大屏名称',
          span: 24,
          labelWidth: 100,
          prop: 'title',
          rules: [{
            required: true,
            message: "请输入大屏名称",
            trigger: "blur"
          }]
        }, {
          label: '密码',
          span: 24,
          type: 'password',
          labelWidth: 100,
          prop: 'password',
        }, {
          label: '发布状态',
          prop: 'status',
          span: 24,
          labelWidth: 100,
          type: 'select',
          dicData: [{
            label: '未发布',
            value: 0
          }, {
            label: '已发布',
            value: 1
          }]
        }]
      },
      page: {
        page: 1,
        size: 50,
        total: 0,
      },
      form: {},
      copyForm: {
        copyTo: 0
      },
      activeName: '',
      visualList: [],
    }
  },
  created () {
    this.categoryOption.addBtn = this.project.isOwner || this.isAdmin
  },
  watch: {
    categoryFilterText(val){
      this.$refs.adminCategoryTree.filter(val)
    },
    projectId(val){
      this.getCategory()
      this.page.total = 0;
      this.visualList = []
    },
    project:{
      handler(val){
        this.categoryOption.addBtn = val.isOwner || this.isAdmin
        if(!val.isOwner){
          this.copyOption.column[0].dicData =[
            {label: "个人空间",value: 0}
          ]
        }else {
          this.copyOption.column[0].dicData =[
            {label: "个人空间",value: 0},
            {label: "本项目空间",value: 1},
          ]
        }

      },
      immediate: true,
      deep: true
    }
  },
  computed:{
    ...mapGetters([
        "isAdmin"
    ]),
    hasAddPermission:function (){
      return this.project.isOwner || this.isAdmin
    },
    hasEditPermission: function (){
      return (this.project.isOwner || this.project.shareRole ===1 )|| this.isAdmin
    },
    hasDelPermission: function (){
      return this.project.isOwner || this.isAdmin
    }
  },
  methods: {
    categoryPermission(key,data){
      if(key === 'addBtn'){
        return  false
      }
      if(this.isAdmin){
        return true
      }
      return this.project.isOwner;
    },
    handleAddCategory(node,data,done,loading){
      data.projectId = this.projectId
      data.categoryValue = uuid()
      addObj(data).then(() => {
        this.$message.success('新增类目成功');
        this.getCategoryList()
        done();
      })
    },
    handleUpdateCategory(node,data,done,loading){
      data.projectId = this.projectId
      updateCategory(data).then(res =>{
        done()
        this.$message.success('修改成功');
        this.getCategoryList()
      })
    },
    handleDelCategory(item,done){
      this.$confirm('是否确认永久删除项目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCategory(item.id).then(() => {
          done()
          this.$message.success('删除成功');
          this.getCategoryList()
        })
      }).catch(() => {

      });
    },
    getCategoryList () {
      getCategoryList({
        current: 1,
        size: 100,
        projectId: this.projectId
      }).then(res => {
        const data = res.data.data;
        this.typeList = data;
      })
    },
    nodeClick(data){
      this.handleSelect(data.categoryValue)
    },
    handleSelect (key) {
      this.activeName = key;
      this.page.page = 1;
      this.getList();
    },
    filterCategory(value,data,node){
      console.log("data",value,data,node)
      if(!value){
        return true
      }
      return data.categoryKey.indexOf(value)!== -1
    },
    getCategory () {
      getCategory({
        projectId:this.projectId
      }).then(res => {
        const data = res.data.data;
        this.typeList = data;
        if(data !==null){
          this.activeName = (this.typeList[0]||{}).categoryValue
          this.getList()
        }
      })
    },
    // 切换分享
    hasShare(value) {
      this.shareType = value
      this.activeName = ''
      this.sharedMap={}
      this.getUserSharedList()
    },
    handleExport (item) {
      getObj(item.id).then(res => {
        const data = res.data.data;
        let mode = {
          detail: JSON.parse(data.config.detail),
          component: JSON.parse(data.config.component)
        }
        var zip = new window.JSZip();
        zip.file("view.js", `const option =${JSON.stringify(mode, null, 4)}`);
        zip.file('index.html', viewHtml);
        zip.generateAsync({ type: "base64" })
          .then(function (content) {
            location.href = "data:application/zip;base64," + content;
          });
      })
    },
    handleCopy (item) {
        this.copyForm = {...this.copyForm,...deepClone(item)}
        this.copyForm.category = undefined
        this.copyForm.title = 'COPY_'+ item.title;
        if(this.copyForm.copyTo === 1){
          this.copyForm.projectId = this.projectId
        }
        this.copy = true;
    },
    confirmCopy(form, done){
      copyObj(form.id,form).then((res) => {
        this.copy = false;
        this.getList();
        this.$message.success('复制成功');
        done()
        const id = res.data.data;
        this.handleEdit({ id })
      })
    },
    confirmUserShare(form,done){
      console.log("分享form",form)
      share2User(form).then(res=>{
        if(res.data.code ===0){
          this.$message.success('分享成功');
        }else {
          this.$message.error('分享失败:'+res.data.message);
        }
        done()
       this.userShare = false
      })
    },
    handleDel (item, index) {
      this.$confirm('是否确认永久删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(item.id).then(() => {
          this.getList();
          this.$message.success('删除成功')

        })
      }).catch(() => {

      });
    },
    handleAdd () {
      this.$router.push({
        path: '/create', query: {
          category: this.activeName,
          projectId: this.projectId
        }
      })
    },
    handleUpdate (item, index) {
      this.form = item
      this.form.category = this.form.category + '';
      this.box = true;
    },
    handleEdit (item) {
      let routeUrl = this.$router.resolve({
        path: '/build/' + item.id
      })
      window.open(routeUrl.href, '_blank');
    },
    handleViews (item) {
      let routeUrl = this.$router.resolve({
        path: '/view/' + item.id
      })
      window.open(routeUrl.href, '_blank');
    },
    handleSave (form, done) {
      updateObj({
        id: this.form.id,
        category: this.form.category,
        password: this.form.password,
        status: this.form.status,
        title: this.form.title,
        projectId: this.projectId
      }).then(() => {
        done();
        this.$message.success('修改成功');
        this.getList()
        this.box = false
      })
    },
    handleCurrentChange (val) {
      this.page.page = val;
      this.getList();
    },
    handleSizeChange (val) {
      this.page.size = val;
      this.getList();
    },
    getList (category) {
      this.visualList = []
      getList({
        category: category || this.activeName,
        projectId: this.projectId,
        current: this.page.page,
        size: this.page.size,
      }).then(res => {
        const {data: {total, records}} = res.data
        this.page.total = total;
        this.visualList = records
        this.initData();
      })
    },
    initData () {
      this.visualList.forEach((ele, index) => {
        this.$set(this.visualList[index], '_menu', false)
      })
    }
  }
}
</script>
<style lang="scss">
@import "@/styles/list.scss";
.el-collapse-item__arrow {
  position: relative;
}
.el-collapse-item__wrap{
  background-color: transparent;
}
</style>
